#include "gameengine.h"

#include <QDebug>
#include <QTimerEvent>
#include <QTime>
#include <QDesktopServices>
#include <QSettings>

const int TIMER_SPEED = 80;

GameEngine::GameEngine(QObject* parent)
    :QObject(parent)
{
    m_timerId = 0;
    m_doEnemyMissile = 1500 / TIMER_SPEED;
    m_GameGml = 0;
    m_myShipGml = 0;

    clearQmlObjects();

    // For random
    QTime time = QTime::currentTime();
    qsrand((uint)time.msec());
    QSettings s("info.vivainio", "qatbowling");
    m_hiScore = s.value("hiscore", QVariant(0)).toInt();


}


GameEngine::~GameEngine()
{
#ifdef Q_OS_SYMBIAN
    delete iVibrate;
#endif

}


QVariant GameEngine::randInt(QVariant low, QVariant high)
{
    // Random number between low and high
    return qrand() % ((high.toInt() + 1) - low.toInt()) + low.toInt();
}


void GameEngine::findQmlObjects()
{
    if (m_GameGml) {
	//qDebug() << "GameEngine::findQmlObjects()";

        m_enemyList.clear();
	//qDebug() << "GameEngine::findQmlObjects() find enemies from: level QML";
        findEnemies(m_GameGml);
        QObjectList l;
        findObjects(m_GameGml, "player", l);
        m_myShipGml = qobject_cast<QDeclarativeItem*>(l.at(0));



    } else {
	//qDebug() << "no root qml yet";
    }

}

void GameEngine::clearQmlObjects()
{
    m_enemyList.clear();
}

void GameEngine::findObjects(QObject *rootObject, const QString& objName, QObjectList& res)
{
    if (rootObject) {
        QObjectList list = rootObject->children();
        QObject* item;
        foreach(item,list) {
            if (item->children().count()>0 && item->objectName()!=objName) {
                //qDebug() << "Enemy childs founds from: " << item->objectName();
                findObjects( item, objName, res);
            } else {
                if (item->objectName()==objName) {
                    //qDebug() << "Enemy child founds: " << item->objectName();
                    QDeclarativeItem* enemy = static_cast<QDeclarativeItem*>(item);
                    res.append(enemy);
                }
            }
        }
    } else {
	//qDebug() << "GameEngine::findEnemies() rootObject NULL";
    }
}


void GameEngine::findEnemies(QObject *rootObject)
{
    if (rootObject) {
        QObjectList list = rootObject->children();
        QObject* item;
        foreach(item,list) {
            if (item->children().count()>0 && item->objectName()!="enemy") {
                //qDebug() << "Enemy childs founds from: " << item->objectName();
                findEnemies(item);
            } else {
                if (item->objectName()=="enemy") {
		    //qDebug() << "Enemy child founds: " << item->objectName();
                    QDeclarativeItem* enemy = static_cast<QDeclarativeItem*>(item);
                    m_enemyList.append(enemy);
                }
            }
        }
    } else {
	//qDebug() << "GameEngine::findEnemies() rootObject NULL";
    }
}


void GameEngine::setGameQml(QObject* o)
{
    m_GameGml = static_cast<QDeclarativeItem*>(o);
}



void GameEngine::doHitTest()
{

    //QDeclarativeItem* missile = 0;
    QDeclarativeItem* enemy = 0;


    if (!m_myShipGml) {
        return;
    }

    //QRectF playerRect = m_myShipGml->boundingRect();
    QRectF playerRect (m_myShipGml->pos(),QSize(m_myShipGml->boundingRect().width(),m_myShipGml->boundingRect().height()));
    // Check ship collision

    for(int e=0; e<m_enemyList.count(); e++) {
        enemy = m_enemyList[e];
        if (enemy->opacity()==0) {
            continue;
        }
        QPointF enemyP =  enemy->pos();
        QRectF enemyR(enemyP,QSize(enemy->boundingRect().width(),enemy->boundingRect().height()));

        if (enemyR.intersects(playerRect)) {
	    //qDebug() << "collide " << e;
            emit collision(m_myShipGml, enemy);

        }

    }


}



QVariant GameEngine::isSymbian()
{
#ifdef Q_OS_SYMBIAN
    return QVariant(true);
#else
    return QVariant(false);
#endif
}

QVariant GameEngine::isMaemo()
{
#ifdef Q_WS_MAEMO_5
    return QVariant(true);
#else
    return QVariant(false);
#endif
}

QVariant GameEngine::isWindows()
{
#ifdef Q_OS_WIN
    return QVariant(true);
#else
    return QVariant(false);
#endif
}

void GameEngine::vibra()
{
#ifdef Q_OS_SYMBIAN
    if (iVibrate){
        TRAPD(err, iVibrate->StartVibraL(4000,KHWRMVibraMaxIntensity));
    }
#endif
}

void GameEngine::fastVibra()
{
#ifdef Q_OS_SYMBIAN
    if (iVibrate){
        TRAPD(err, iVibrate->StartVibraL(100,KHWRMVibraMaxIntensity));
    }
#endif
}

void GameEngine::doFrame()
{

    doHitTest();

}

int GameEngine::hiScore() const
{
    return m_hiScore;
}

void GameEngine::setHiScore(int arg)
{
    QSettings s("info.vivainio", "qatbowling");
    s.setValue("hiscore", QVariant(arg));
    m_hiScore = arg;
}

